package order

import (
	"fmt"
	"web/global"
	"web/models"
	"web/pkg/util"
)

type OrderService struct {
}

// 创建订单服务实例
func NewOrderService() *OrderService {
	return &OrderService{}
}

// Get 根据ID获取订单
func (s *OrderService) Get(id uint) (*models.LaOrder, error) {
	var order models.LaOrder
	err := global.DB.First(&order, id).Error
	if err != nil {
		return nil, fmt.Errorf("获取订单失败: %w", err)
	}
	return &order, nil
}

// Gets 获取订单列表 - 直接使用Where条件
func (s *OrderService) Gets(mapParam map[string]interface{}, pageInfo util.PageInfo) ([]*models.LaOrder, util.NextPageInfo, error) {
	var orders []*models.LaOrder

	// 初始化查询对象 - 直接使用GORM查询
	q := global.DB.Model(&models.LaOrder{})

	// 遍历参数，直接添加Where条件
	for key, value := range mapParam {
		switch key {
		case "status":
			if status, ok := value.(int); ok && status > 0 {
				q = q.Where("status = ?", status)
			}
		case "uid":
			if uid, ok := value.(uint64); ok && uid > 0 {
				q = q.Where("uid = ?", uid)
			}
		case "order_no":
			if orderNo, ok := value.(string); ok && orderNo != "" {
				q = q.Where("order_no = ?", orderNo)
			}
		case "pay_status":
			if payStatus, ok := value.(uint8); ok && payStatus > 0 {
				q = q.Where("pay_status = ?", payStatus)
			}
		case "pay_type":
			if payType, ok := value.(int); ok && payType > 0 {
				q = q.Where("pay_type = ?", payType)
			}
		case "order_type":
			if orderType, ok := value.(uint8); ok && orderType > 0 {
				q = q.Where("order_type = ?", orderType)
			}
		case "order_status":
			if orderStatus, ok := value.(uint8); ok && orderStatus > 0 {
				q = q.Where("order_status = ?", orderStatus)
			}
		case "is_delete":
			if isDelete, ok := value.(uint8); ok {
				q = q.Where("is_delete = ?", isDelete)
			}
		}
	}

	// 处理时间范围查询
	if startTime, ok := mapParam["service_time_start"].(string); ok && startTime != "" {
		q = q.Where("service_time >= ?", startTime)
	}
	if endTime, ok := mapParam["service_time_end"].(string); ok && endTime != "" {
		q = q.Where("service_time <= ?", endTime)
	}

	// 处理创建时间范围查询
	if startTime, ok := mapParam["created_at_start"].(string); ok && startTime != "" {
		q = q.Where("created_at >= ?", startTime)
	}
	if endTime, ok := mapParam["created_at_end"].(string); ok && endTime != "" {
		q = q.Where("created_at <= ?", endTime)
	}

	// 处理金额范围查询
	if minAmount, ok := mapParam["order_amount_min"].(float64); ok && minAmount > 0 {
		q = q.Where("order_amount >= ?", minAmount)
	}
	if maxAmount, ok := mapParam["order_amount_max"].(float64); ok && maxAmount > 0 {
		q = q.Where("order_amount <= ?", maxAmount)
	}

	// 添加排序
	finalQuery := q.Order("created_at DESC")

	if pageInfo != nil {
		// 执行分页查询
		nextPage, err := util.Paginate(finalQuery, pageInfo, &orders)
		if err != nil {
			return nil, nil, fmt.Errorf("分页查询失败: %w", err)
		}
		return orders, nextPage, nil
	}

	// 查询所有记录
	err := finalQuery.Find(&orders).Error
	if err != nil {
		return nil, nil, fmt.Errorf("查询订单列表失败: %w", err)
	}
	return orders, nil, nil
}

// Create 创建订单
func (s *OrderService) Create(order *models.LaOrder) error {
	err := global.DB.Create(order).Error
	if err != nil {
		return fmt.Errorf("创建订单失败: %w", err)
	}
	return nil
}

// Update
func (s *OrderService) Update(order *models.LaOrder) error {
	err := global.DB.Save(order).Error
	if err != nil {
		return fmt.Errorf("更新订单失败: %w", err)
	}
	return nil
}

// Delete 删除订单
func (s *OrderService) Delete(id uint) error {
	err := global.DB.Delete(&models.LaOrder{}, id).Error
	if err != nil {
		return fmt.Errorf("删除订单失败: %w", err)
	}
	return nil
}

// ExistByOrderNo 检查订单号是否存在
func (s *OrderService) ExistByOrderNo(orderNo string) (bool, error) {
	var count int64
	err := global.DB.Model(&models.LaOrder{}).Where("order_no = ?", orderNo).Count(&count).Error
	if err != nil {
		return false, fmt.Errorf("检查订单号失败: %w", err)
	}
	return count > 0, nil
}

// GetByOrderNo 根据订单号获取订单
func (s *OrderService) GetByOrderNo(orderNo string) (*models.LaOrder, error) {
	var order models.LaOrder
	err := global.DB.Where("order_no = ?", orderNo).First(&order).Error
	if err != nil {
		return nil, fmt.Errorf("根据订单号获取订单失败: %w", err)
	}
	return &order, nil
}

// GetByUid 根据用户ID获取订单列表
func (s *OrderService) GetByUid(uid uint64, pageInfo util.PageInfo) ([]*models.LaOrder, util.NextPageInfo, error) {
	filters := map[string]interface{}{
		"uid": uid,
	}
	return s.Gets(filters, pageInfo)
}

// Exists 检查订单是否存在
func (s *OrderService) Exists(id uint) (bool, error) {
	var order models.LaOrder
	err := global.DB.First(&order, id).Error
	if err != nil {
		return false, fmt.Errorf("根据ID获取订单失败: %w", err)
	}
	return true, nil
}

// GetByStatus 根据状态获取订单列表
func (s *OrderService) GetByStatus(status int, pageInfo util.PageInfo) ([]*models.LaOrder, util.NextPageInfo, error) {
	filters := map[string]interface{}{
		"status": status,
	}
	return s.Gets(filters, pageInfo)
}
